#include "uploadbutton.h"

uploadbutton::uploadbutton(const QString& url,QWidget *parent) : QPushButton(parent)
{
    this->setText("上传");
    base_url=url+"upload";
    manager=new QNetworkAccessManager(this);
    connect(this,&QPushButton::clicked,this,&uploadbutton::upLoad);//连接点击处理函数
}


void uploadbutton::upLoad()
{
    QString filePath = QFileDialog::getOpenFileName(this);
    if (filePath.isEmpty()) {
        // 用户取消或没有选择文件
        return;
    }

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file:" ;//<< file.errorString();
        return;
    }

    QString fileName = QFileInfo(filePath).fileName(); // 更安全的获取文件名

    QUrl url(base_url);
    QNetworkRequest request(url); // 构建请求

    // 设置上传请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(file.size()));
    request.setRawHeader("filename",fileName.toUtf8());

    // 使用post方法发送请求，并将multiPart的所有权传递给它
    respons = manager->post(request, file.readAll());
    file.close();

    // 连接信号以处理响应
    connect(respons, &QNetworkReply::finished, this, [this]() {
        this->handerUpLoad(); // 确保handerUpLoad函数接受QNetworkReply*作为参数
        respons->deleteLater(); // 确保在handerUpLoad函数处理完回复后删除它
    });
}

void uploadbutton::handerUpLoad()
{
    if(respons->error()!=QNetworkReply::NoError)
    {
        qDebug()<<"上传失败";
    }
    else qDebug()<<"上传成功";

}
